﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Xml.Linq;

namespace Fireball.OpenXML.Word
{
    public sealed class StyleTableProperties :OpenXMLEntity
    {

        /// <summary>
        /// Table Indent from leading margin
        /// </summary>
        public decimal? Indent
        {
            get;
            set;
        }

        [DefaultValue(WidthType.Dxa)]
        public WidthType IndentWidthType
        {
            get;
            set;
        }

        public TableCellMarginDefaults TableCellMargins
        {
            get;
            set;
        }

        private void ParseInternal(XElement xTablePr)
        {
            if (xTablePr.Name.LocalName != "tblPr")
                throw new Exception("Invalid node for tblPr");

            var indent = xTablePr.Element(NS.WM + "tblInd");

            if (indent != null)
            {
                this.Indent = decimal.Parse(indent.Attribute(NS.WM + "w").Value);
                this.IndentWidthType = indent.Attribute(NS.WM + "type").
                    Value.GetEnum<WidthType>();
            }

            var tblMargin = xTablePr.Element(NS.WM + "tblCellMar");

            if (tblMargin != null)
            {
                this.TableCellMargins = TableCellMarginDefaults.Parse(tblMargin);
            }
        }

        public static StyleTableProperties Parse(XElement xTablePr)
        {
            var s = new StyleTableProperties();
            s.ParseInternal(xTablePr);
            return s;
        }


        public override System.Xml.Linq.XContainer ToXml()
        {
            XElement tblPr = new XElement(NS.WM + "tblPr");

            if (this.Indent != null)
                tblPr.Add(new XElement(NS.WM + "tblInd",
                    new XAttribute(NS.WM + "w", this.Indent.Value),
                    new XAttribute(NS.WM + "type", this.IndentWidthType.ToOffice())));

            if (this.TableCellMargins != null)
                tblPr.Add(this.TableCellMargins.ToXml());

            return tblPr;
        }
    }
}
